<template>
    <div v-loading="isLoading">
        <div class="top-div">
            <div class="title">
                <div style="color:aqua;float: left;">抖阳直播间</div>
                <div  @click="$router.push('/home/live')" class="router">返回首页</div>
            </div>
            <div>
                <img :src="address.minioUrl+'image/'+userInfo?.avatar" class="avatar-img">
            </div>
        </div>

        <div class="container">
            <div class="main-container">
                <div class="main-left">
                    <div style="margin-left: 1%;width: 98.6%;">
                        <img :src="address.minioUrl+'image/'+live?.presenterAvatar" class="live-img">
                        <div style="margin-left: 10px;margin-top: -15px;float: left;">
                            <h3>{{live?.title}}</h3>
                            <span style="color: #999;">{{live?.presenterName}}</span>
                        </div>

                        <div style="float: right;margin-left: 10px;">点赞量：{{likedCount>10000?likedCount/10000+'万':likedCount}}</div>
                    </div>
                    <div class="live-player" @click="liveLive()">
                        <livePlayer :channelKey="live?.channelKey"></livePlayer>
                    </div>


                </div>


                <div class="main-right" :disabled="!isLogin">
                    <div style="text-align: center;">直播间观众({{livePropleList.length}})</div>
                    <div class="main-right-top">
                        <div>
                            <div class="live-person-container" v-for="(livePerson,index) in livePropleList" :key="index" style="height: 80%;">
                                <div class="live-person-info">
                                    <img :src="address.minioUrl + 'image/' + livePerson.avatar" class="watch-img">
                                    <div>{{ livePerson.userName.slice(0, 9)}}<span v-if="livePerson.userName.length>8">...</span></div>
                                </div>
                                <div class="like-count">点赞量：{{ livePerson.likeCount>10000?livePerson.likeCount/10000+'万':livePerson.likeCount ?? 0}}</div>
                            </div>
                        </div>
                    </div>

                    <div class="live-chat">
                        <div v-for="(userLifeMessage,index) in userLifeMessageList" :key="index">
                            <div><span style="color:#999">{{userLifeMessage.userName}}</span>：<span style="color:azure">{{userLifeMessage.content}}</span></div>
                    
                        </div>
                    </div>

                    <div class="live-send-message">
                        <input @keyup.enter="sendMessage" v-model="userInput" class="live-send-message-input" type="text" placeholder="请输入内容">
                    </div>
                </div>
            </div>
        </div>
    </div>


    <el-dialog v-model="showLoginView" width="800" style="height: 500px;border-radius: 20px;background: linear-gradient(to bottom, #fbf0f2 10%, #ffffff);color: black;" center>
        <template #header>
            <h2 style="margin-top: 0px;">登录</h2>
        </template>
        <LoginView></LoginView> 
    </el-dialog>
</template>


<script setup lang="ts">
    import { address } from '@/base/address'
    import request from '@/base/request'
    import Live from '@/types/live/Live'
    import { ElMessage } from 'element-plus'
    import { ref, onMounted,defineProps,nextTick } from 'vue'
    import getUserInfo from '@/utils/getUserInfo'
    import UserInfo from '@/types/user/UserInfo'
    import LiveProple from '@/types/live/LiveProple'
    import UserLifeMessage from '@/types/user/UserLifeMessage'
    import checkLogin from '@/utils/checkLogin'
    const doubleClick=ref(0)

    const userLifeMessageList=ref<UserLifeMessage[]>([])
    const livePropleList=ref<LiveProple[]>([])
    const props=defineProps(['presenterId'])
    const live = ref<Live>()
    const likedCount=ref(0)
    let html=document.documentElement
    html.className='dark'
    const isLoading=ref(false)
    const reGet=ref(1)
    const userInfo=ref<UserInfo>()
    const userInput=ref('')
    const isLogin=ref(false)
    const showLoginView=ref(false)
    let socket:WebSocket
    let timer
    const liveLive=()=>{
        doubleClick.value++
        if(doubleClick.value===2){
            doubleClick.value=0
            if(!checkLogin()){
                showLoginView.value=true
                return
            }
            request.post(`/user/userVideoLiked/liveLike/${live.value.id}`)
        }else if(doubleClick.value===1){
            clearTimeout(timer)
            timer=setTimeout(()=>{
                doubleClick.value=0
            },500)
        }
    }
    const getLive=async ()=>{
        isLoading.value=true
        let response;
        while(isLoading.value && reGet.value<=3){
            try{
                response=(await request.get('/video/live/getLiveByPresenterId',{params:{presenterId:props.presenterId}})).data
                if(response.code===200){
                    live.value=response.data
                    isLoading.value=false
                }else{
                    ElMessage.error(`获取直播间失败,第${reGet.value}次尝试`)
                    reGet.value++
                    await new Promise(resolve => setTimeout(resolve, 2000))
                }
            }catch(error){
                ElMessage.error(`获取直播间失败,第${reGet.value}次尝试`)
                reGet.value++
                await new Promise(resolve => setTimeout(resolve, 2000))
            }
        }
        if(isLoading.value){
            ElMessage.error(`获取直播间失败：${response.msg}`)
        }
    }
    const connectSocket=()=>{
        socket=new WebSocket(`${address.socketUrl}/socket/ws/${live.value.id}/${localStorage.getItem('token')}`)

        socket.onopen=async()=>{
            console.log('连接成功')
            await getLivePropleList()
        }
        socket.onmessage=(event)=>{
            const userLifeMessage=JSON.parse(event.data)
            if(userLifeMessage.type===1){
                userLifeMessageList.value.push(userLifeMessage)
                nextTick(()=>{scrollToBottom()}) 
            }
            else if(userLifeMessage.type===2)getLivePropleList()
            else if(userLifeMessage.type===3)livePropleList.value.splice(livePropleList.value.findIndex(item=>item.userId===userLifeMessage.userId),1)
            else if(userLifeMessage.type===4){
                likedCount.value++
                livePropleList.value.forEach(item=>{
                    if(item.userId==userLifeMessage.userId){
                        item.likeCount++
                    }
                })
            }
        }
}
    

    const sendMessage=()=>{
        if(userInput.value.trim() === '') {
            ElMessage.warning('请输入内容');
            return;
        }
        if(!isLogin.value){
            ElMessage.error('请先登录')
            showLoginView.value=true
            return
        }
        socket.send(userInput.value)
        userInput.value=''
    }

    const scrollToBottom=()=>{
        const liveChat=document.querySelector('.live-chat')
        if(liveChat){
            liveChat.scrollTop=liveChat.scrollHeight
        }
    }


    const getLivePropleList=async ()=>{
        const response=(await request.get('/user/userVideoLiked/getLivePeopleList',{params:{liveId:live.value.id}})).data
        if(response.code===200){
            livePropleList.value=response.data
        }else{
            ElMessage.info('获取直播间观众失败')
        }
    }


    onMounted(async ()=>{
        isLogin.value=await checkLogin()
        if(!isLogin.value){
            ElMessage.warning('建议登录后观看')
            showLoginView.value=true
        }
        userInfo.value=await getUserInfo(null)
        await getLive()
        if(isLogin.value){
            connectSocket()
        }
        await getLivePropleList()
        
   

        
    })


</script>

<style scoped>
    .router {
        margin-left: 30px;
        margin-top: 5px;
        font-size: 16px;
        cursor: pointer;
        float: right;
    }

    .router:hover {
        animation: router-hover 0.3s;
    }

    @keyframes router-hover {
        50% {
            margin-top: 0px;
        }
        100% {
            margin-top: 5px;
        }
    }

    .title {
        text-align: left;
        float: left;
        font-size: 23px;
        font-weight: bold;
        margin-left: 1%;
        margin-top: 0.5%;
    }

    .top-div {
        text-align: right;
        height: 50px;
        min-width: 1000px;
        box-shadow: 0 6px 10px 0 rgba(84, 84, 84, 0.5);
    }

    .avatar-img {
        width: 40px;
        height: 40px;
        border-radius: 50%;
    }

    .main-container {
        display: flex;
        margin-top: 10px;
        width: 90%;
        margin-left: 5%;
        min-width: 1000px;
        height: calc(91vh - 90px); 
        box-sizing: border-box;
        
    }



    .main-left, .main-right {
        float: none;
        width: auto;
        background-color: rgb(34, 34, 34);
        border-radius: 10px;
        border: 0.5px solid #5f5e5e;
        flex: 1;
        padding: 10px;
        box-sizing: border-box;
        height: 100%; /* 确保 main-left 和 main-right 高度一致 */
        margin-top: 30px;
    }

    .main-right {
        margin-left: 1%;
        display: flex;
        flex-direction: column;
    }

    .main-left {
        flex: 3;
    }

    .live-player {
        clear: both;
        margin-top: 8%;
        padding-top: 56.25%;
        position: relative;
    }

    .live-img {
        float: left;
        width: 65px;
        height: 65px;
        border-radius: 50%;
    }

    .main-right-top {
        text-align: center;
        height: 30%;
        border-bottom: 1px solid #5f5e5e;
        cursor: pointer;
        transition: 0.3s;
        overflow-y: auto;
    }

    .main-right-top::-webkit-scrollbar {
        display: none; /* 隐藏滚动条 */
    }

    .main-right-top:hover {
        height: 60%;
    }

    .live-person-container {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 10px;
    }

    .live-person-info {
        display: flex;
        align-items: center;
    }

    .watch-img {
        width: 30px;
        height: 30px;
        border-radius: 50%;
        margin-right: 10px;
    }

    .like-count {
        font-size: 13px;
        color: #6c6b6b;
        text-align: right;
    }

    .live-chat {
        flex: 1;
        overflow-y: auto;
        padding: 10px;
    }

    .live-chat::-webkit-scrollbar {
        display: none; /* 隐藏滚动条 */
    }

    .live-send-message {
        height: 10%;
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 0 10px;
        border-top: 1px solid #5f5e5e;
    }

    .live-send-message-input {
        width: 100%;
        height: 100%;
        border: none;
        background-color: transparent;
        font-size: 20px;
    }

    .live-send-message-input:focus {
        outline: none;
    }
</style>